<template>
  <div>
    <base-load-page
      ref="baseLoadPageRef"
      :loadState="pageLoad.loadState"
      :description="pageLoad.description"
      :pageLoadButton="[{ text: '重新加载', callBack: () => getBaseDataAxios() }]"
      :padding="parseInt(String(scss.appPagePadding))"
      :margin="0"
      background="rgba(0,0,0,0)"
      class="base-load-page"
    >
      <div class="page">
        <el-scrollbar v-if="baseData">
          <div class="page-mian-box">
            <operation-statistics :statisticsData="homeCensusData"></operation-statistics>
            <home-module title="注册统计" style="min-width: max(800px, 70%)">
              <div id="registrationStatistics" style="width: 100%; height: 100%"></div>
            </home-module>
            <home-module title="统计报表">
              <user-register :statisticsData="homeCensusData"></user-register>
            </home-module>
            <home-module v-if="baseData.dramaPayRankList.length > 0" title="付费短剧排行">
              <home-ranking-list :rankList="baseData.dramaPayRankList"></home-ranking-list>
            </home-module>
            <home-module v-if="baseData.userPayRankList.length > 0" key="home-module-2" title="付费用户排行">
              <home-ranking-list :rankList="baseData.userPayRankList"></home-ranking-list>
            </home-module>
            <home-module title="付费统计">
              <div class="grid-list-box">
                <template v-for="(item, _index) in baseData.payStatisticsList" :key="_index">
                  <home-grid-item :icon="item.icon" :name="item.name" :color="item.color" :numb="item.numb" :suffix="item.suffix"></home-grid-item>
                </template>
              </div>
            </home-module>
            <!-- 用户统计 -->
            <home-module title="用户统计">
              <div class="grid-list-box">
                <template v-for="(item, _index) in baseData.userStatisticsList" :key="_index">
                  <home-grid-item :icon="item.icon" :name="item.name" :color="item.color" :numb="item.numb" :suffix="item.suffix"></home-grid-item>
                </template>
              </div>
            </home-module>
            <!-- 充值分析 -->
            <home-module v-if="baseData.payAnalyse" key="home-module-3" title="充值分析">
              <div class="list-bar-box">
                <home-list-bar-module name="本周充值金额" :numb="baseData.payAnalyse.currWeekAmount" color="var(--el-color-primary)"></home-list-bar-module>
                <home-list-bar-module name="上周充值金额" :numb="baseData.payAnalyse.lastWeekAmount" color="var(--el-color-error)"></home-list-bar-module>
              </div>
              <div class="charts-type1-box">
                <div id="payAnalyse" style="width: 100%; height: 100%"></div>
              </div>
            </home-module>
            <!-- 用户/会员分析 -->
            <home-module title="用户/会员分析">
              <div class="charts-type2-box">
                <div class="charts-box">
                  <div class="charts">
                    <div id="userAnalyseVIP" style="width: 100%; height: 100%"></div>
                  </div>
                  <div class="info-box">
                    <rest-count-to :endVal="baseData.userAnalyse.currWeekVip" color="var(--el-color-danger)" fontSize="20px"></rest-count-to>
                    <span class="unit">人</span>
                  </div>
                  <div class="name">本周新增会员</div>
                </div>
                <div class="charts-box">
                  <div class="charts">
                    <div id="userAnalyseUSER" style="width: 100%; height: 100%"></div>
                  </div>
                  <div class="info-box">
                    <rest-count-to :endVal="baseData.userAnalyse.currWeekUser" color="var(--el-color-danger)" fontSize="20px"></rest-count-to>
                    <span class="unit">人</span>
                  </div>
                  <div class="name">本周新增用户</div>
                </div>
              </div>
            </home-module>
            <!-- 追剧分析 -->
            <home-module v-if="baseData.chasingAnalyse" key="home-module-4" title="追剧分析">
              <div class="list-bar-box">
                <home-list-bar-module
                  name="本周追剧人数"
                  :numb="baseData.chasingAnalyse.currWeekChasingNum"
                  color="var(--el-color-primary)"
                  unit="人"
                ></home-list-bar-module>
                <home-list-bar-module
                  name="上周追剧人数"
                  :numb="baseData.chasingAnalyse.lastWeekChasingNum"
                  color="var(--el-color-error)"
                  unit="人"
                ></home-list-bar-module>
              </div>
              <div class="charts-type1-box">
                <div id="chasingAnalyse" style="width: 100%; height: 100%"></div>
              </div>
            </home-module>
            <!-- 消费分析 -->
            <home-module title="消费分析">
              <div class="list-bar-box">
                <home-list-bar-module
                  name="本周消费金额"
                  :numb="baseData.consumptionAnalyse.currWeekConsumption"
                  color="var(--el-color-primary)"
                ></home-list-bar-module>
                <home-list-bar-module
                  name="上周消费金额"
                  :numb="baseData.consumptionAnalyse.lastWeekConsumption"
                  color="var(--el-color-error)"
                ></home-list-bar-module>
              </div>
              <div class="charts-type1-box">
                <div id="consumptionAnalyse" style="width: 100%; height: 100%"></div>
              </div>
            </home-module>
            <div v-for="item in [1, 2, 3, 4, 5]" :key="item" style="height: 0; margin-top: 0; margin-bottom: 0; opacity: 0"></div>
          </div>
        </el-scrollbar>
      </div>
    </base-load-page>
  </div>
</template>

<script setup lang="ts">
  import type { ECharts } from 'echarts/core';
  import HomeRankingList from './components/home-ranking-list/home-ranking-list.vue';
  import OperationStatistics from './components/operation-statistics/operation-statistics.vue';
  import userRegister from './components/user-register/user-register.vue';
  import HomeListBarModule from './components/home-list-bar-module/home-list-bar-module.vue';
  import HomeModule from './components/home-module/home-module.vue';
  import HomeGridItem from './components/home-grid-item/home-grid-item.vue';
  import { getAxiosData } from './get-axios-data';
  import { storeToRefs } from 'pinia';
  import { useCssVar, useThrottleFn } from '@vueuse/core';
  import scss from '@/styles/module/export.module.scss';
  import RestCountTo from '@/components/rest/rest-count-to/rest-count-to.vue';

  import { areaChart, barChart, gaugeChart, initMyEChart, lineChart } from '@/utils/echarts';
  import { type HomeCensus, getHomeData } from '@/api/home';
  import { formatDateStr, getDateRange } from '@/utils/time';
  import { getRandomNumber, splitNumberWithSeed } from '@/utils/common.ts';

  type _BaseData = $UnwrapPromise<typeof getAxiosData>;

  type BaseData = _BaseData & {
    thisWeekAddUserNumList?: number[];
  };

  /** 是否显示假数据 */
  const displayMode = false;
  const randomSeed = formatDateStr(new Date());

  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });

  const myChartArr = shallowRef<(ECharts | undefined)[]>([]);

  const baseData = shallowRef<BaseData | null>(null);

  const baseLoadPageRef: $RefComp<'BaseLoadPage'> = ref(null);

  const homeCensusData = ref<HomeCensus>({});

  /** 是否为深色主题 */
  const { globalTheme } = storeToRefs(useGlobalStore());
  watch(globalTheme, initMyAllEChart);

  const myObserver = new ResizeObserver(
    useThrottleFn(() => {
      myChartArr.value.forEach((echart) => {
        echart && echart.resize && echart.resize();
      });
    }, 200)
  );

  onActivated(() => {
    myObserver.disconnect();
    baseLoadPageRef.value?.$el && myObserver.observe(baseLoadPageRef.value.$el);
  });

  onDeactivated(() => {
    myObserver.disconnect();
  });

  onBeforeMount(() => {
    getBaseDataAxios();
  });

  onBeforeUnmount(() => {
    myObserver.disconnect();
    myChartArr.value.forEach((echart) => {
      echart && echart.dispose && echart.dispose();
    });
    myChartArr.value = [];
  });

  /**
   * 得到基础数据
   */
  async function getBaseDataAxios() {
    try {
      pageLoad.loadState = true;
      baseData.value = await getAxiosData();
      const { data } = await getHomeData();
      if (displayMode) {
        // 假数据
        homeCensusData.value.todayConsume = getRandomNumber(400000, 600000, randomSeed, true);
        homeCensusData.value.todayEarnings = getRandomNumber(600000, 1000000, randomSeed, true);
        homeCensusData.value.yesterdayEarnings = getRandomNumber(400000, 600000, randomSeed, true);
        homeCensusData.value.weekEarnings = getRandomNumber(3500000, 5500000, randomSeed, true);
        homeCensusData.value.monthEarnings = getRandomNumber(15000000, 18000000, randomSeed, true);
        homeCensusData.value.roi = getRandomNumber(1, 1.6, randomSeed, true);
        homeCensusData.value.vipUserCount = getRandomNumber(3000000, 4000000, randomSeed);
        homeCensusData.value.dramaCount = 684;
        homeCensusData.value.orderCount = getRandomNumber(16666, 20000, randomSeed);
        homeCensusData.value.orderCountAmount = getRandomNumber(30000000, 50000000, randomSeed, true);
        homeCensusData.value.consumptionBalance = getRandomNumber(10000000, 11500000, randomSeed, true);

        homeCensusData.value.todayAddUserNum = getRandomNumber(5000, 8000, `${randomSeed}6`);
        homeCensusData.value.todayLoginUserNum = getRandomNumber(5000, 8000, `${randomSeed}6`);
        homeCensusData.value.threeDaysAddUserNum = getRandomNumber(15000, 18000, randomSeed);
        homeCensusData.value.weekAddUserNum = getRandomNumber(35000, 240000, randomSeed);
        homeCensusData.value.weekActiveUserNum = getRandomNumber(30000, 200000, randomSeed);
        homeCensusData.value.monthActiveUserNum = getRandomNumber(800000, 1000000, randomSeed);

        baseData.value.dramaPayRankList.forEach((v) => {
          v.value = getRandomNumber(500000, 800000, randomSeed + v.title, true);
        });
        baseData.value.userPayRankList.forEach((v) => {
          v.value = getRandomNumber(10000, 30000, randomSeed + v.title, true);
        });
        baseData.value.payStatisticsList.forEach((v) => {
          if (v.name.indexOf('今日付费金额') !== -1) {
            v.numb = getRandomNumber(10000, 30000, randomSeed + v.name, true);
          }
          if (v.name.indexOf('今日付费用户') !== -1) {
            v.numb = getRandomNumber(5000, 8000, randomSeed + v.name);
          }
          if (v.name.indexOf('本周付费金额') !== -1) {
            v.numb = getRandomNumber(70000, 210000, randomSeed + v.name, true);
          }
          if (v.name.indexOf('本周付费用户') !== -1) {
            v.numb = getRandomNumber(35000, 200000, randomSeed + v.name);
          }
        });
        baseData.value.userStatisticsList.forEach((v) => {
          if (v.name.indexOf('用户总数') !== -1) {
            v.numb = getRandomNumber(4000000, 4100000, randomSeed);
          }
          if (v.name.indexOf('会员总数') !== -1) {
            v.numb = getRandomNumber(3000000, 4000000, randomSeed);
          }
          if (v.name.indexOf('追剧人数') !== -1) {
            v.numb = getRandomNumber(3000000, 3300000, randomSeed + v.name);
          }
          if (v.name.indexOf('观看人数') !== -1) {
            v.numb = getRandomNumber(3000000, 2500000, randomSeed + v.name);
          }
        });

        baseData.value.payAnalyse.currWeekAmount = getRandomNumber(3500000, 5500000, randomSeed, true);
        baseData.value.payAnalyse.lastWeekAmount = getRandomNumber(3000000, 5000000, randomSeed, true);

        baseData.value.userAnalyse.currWeekVip = getRandomNumber(5000, 8000, `${randomSeed}6`);
        baseData.value.userAnalyse.currWeekUser = getRandomNumber(35000, 240000, randomSeed);

        baseData.value.chasingAnalyse.currWeekChasingNum = getRandomNumber(50000, 60000, randomSeed);
        baseData.value.chasingAnalyse.lastWeekChasingNum = getRandomNumber(40000, 50000, `${randomSeed}lastWeekChasingNum`);

        baseData.value.consumptionAnalyse.currWeekConsumption = getRandomNumber(3500000, 5500000, randomSeed, true);
        baseData.value.consumptionAnalyse.lastWeekConsumption = getRandomNumber(3500000, 5500000, `${randomSeed}lastWeekConsumption`);
      } else {
        homeCensusData.value = data;
      }
      baseData.value.thisWeekAddUserNumList = data.thisWeekAddUserNumList ?? new Array(7).fill(0);
      pageLoad.loadState = false;
      myChartArr.value = [];
      initMyAllEChart();
    } catch (err) {
      pageLoad.loadState = 'err';
      pageLoad.description = String((err as Record<string, unknown>).msg || '') || '获取数据失败';
    }
  }

  /**
   * 初始化表格
   */
  function initMyAllEChart() {
    myChartArr.value.forEach((echart) => {
      echart && echart.dispose && echart.dispose();
    });
    myChartArr.value = [];
    nextTick(() => {
      const success = unref(useCssVar('--el-color-success'))!;
      const primary = unref(useCssVar('--el-color-primary'))!;
      const theme = unref(globalTheme);
      const data: (typeof baseData)['value'] = baseData.value ? JSON.parse(JSON.stringify(baseData.value)) : undefined;
      if (data) {
        if (displayMode) {
          const val = JSON.parse(JSON.stringify(data.payAnalyse.dataset));
          val.series.forEach((v: any) => {
            if (v.name === '本周充值金额') {
              v.data = splitNumberWithSeed(baseData.value!.payAnalyse.currWeekAmount, 7, randomSeed);
            } else {
              v.data = splitNumberWithSeed(baseData.value!.payAnalyse.lastWeekAmount, 7, randomSeed);
            }
          });
          data.payAnalyse && myChartArr.value.push(initMyEChart('payAnalyse', theme, lineChart(val)));
        } else {
          data.payAnalyse && myChartArr.value.push(initMyEChart('payAnalyse', theme, lineChart(data.payAnalyse.dataset)));
        }
        data.userAnalyse && myChartArr.value.push(initMyEChart('userAnalyseVIP', theme, gaugeChart(data.userAnalyse.vipDataset, success)));
        data.userAnalyse && myChartArr.value.push(initMyEChart('userAnalyseUSER', theme, gaugeChart(data.userAnalyse.userDataset, primary)));
        if (displayMode) {
          const val = JSON.parse(JSON.stringify(data.chasingAnalyse.dataset));
          val.series.forEach((v: any) => {
            if (v.name === '本周追剧人数') {
              v.data = splitNumberWithSeed(baseData.value!.chasingAnalyse.currWeekChasingNum, 7, randomSeed);
            } else {
              v.data = splitNumberWithSeed(baseData.value!.chasingAnalyse.lastWeekChasingNum, 7, randomSeed);
            }
          });
          data.chasingAnalyse && myChartArr.value.push(initMyEChart('chasingAnalyse', theme, lineChart(val)));
        } else {
          data.chasingAnalyse && myChartArr.value.push(initMyEChart('chasingAnalyse', theme, barChart(data.chasingAnalyse.dataset)));
        }
        if (displayMode) {
          const val = JSON.parse(JSON.stringify(data.consumptionAnalyse.dataset));
          val.series.forEach((v: any) => {
            if (v.name === '本周消费金额') {
              v.data = splitNumberWithSeed(baseData.value!.consumptionAnalyse.currWeekConsumption, 7, randomSeed);
            } else {
              v.data = splitNumberWithSeed(baseData.value!.consumptionAnalyse.lastWeekConsumption, 7, randomSeed);
            }
          });
          data.consumptionAnalyse && myChartArr.value.push(initMyEChart('consumptionAnalyse', theme, lineChart(val)));
        } else {
          data.consumptionAnalyse && myChartArr.value.push(initMyEChart('consumptionAnalyse', theme, areaChart(data.consumptionAnalyse.dataset)));
        }

        data.thisWeekAddUserNumList &&
          myChartArr.value.push(
            initMyEChart(
              'registrationStatistics',
              theme,
              areaChart({
                series: [
                  {
                    'name': '近七日注册用户数(人)',
                    'data': data.thisWeekAddUserNumList,
                    // 'data': [
                    //   getRandomNumber(5000, 8000, randomSeed),
                    //   getRandomNumber(3000, 8000, `${randomSeed}1`),
                    //   getRandomNumber(4000, 8000, `${randomSeed}2`),
                    //   getRandomNumber(5000, 8000, `${randomSeed}3`),
                    //   getRandomNumber(5000, 8000, `${randomSeed}4`),
                    //   getRandomNumber(5000, 8000, `${randomSeed}5`),
                    //   getRandomNumber(5000, 8000, `${randomSeed}6`),
                    // ],
                  },
                ],
                xAxis: {
                  data: getDateRange(7),
                  axisLabel: {
                    formatter: (val: string) => val.substring(5),
                  },
                },
              })
            )
          );
      }
    });
  }
</script>

<style lang="scss" scoped>
  .base-load-page {
    width: 100%;

    .page {
      width: calc(100% + $app-page-padding);
      height: 100%;
      padding-right: 0;
      margin-right: -$app-page-padding;
      overflow: hidden;

      .page-mian-box {
        @include flex(row, wrap, flex-start, stretch, stretch);
        width: 100%;

        /* stylelint-disable-next-line order/order */
        @for $i from 0 to 12 {
          .global-slide-up-animation:nth-child(#{$i}) {
            animation-delay: #{0.3 + $i * 0.05}s;
          }
        }
      }
    }
  }

  .grid-list-box {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    width: 100%;
    height: 100%;
  }

  .list-bar-box {
    @include flex(row, nowrap, space-around, center, center);
    padding-top: 10px;
  }

  .charts-type1-box {
    width: 100%;
    height: 174px;
    padding-top: 10px;
  }

  .charts-type2-box {
    @include flex(row, nowrap, center center, center);
    height: 100%;
    padding-bottom: 15px;

    .charts-box {
      @include flex(column, nowrap, center center, center);
      flex: 1;
      min-width: 140px;
      padding-top: 6px;

      .charts {
        width: 140px;
        height: 140px;
      }

      .info-box .unit {
        margin-left: 3px;
        font-size: calc(var(--my-change-base12-2x-size) - 2px);
        line-height: 1em;
        color: $c-text-1;
      }

      .name {
        margin-top: 5px;
        font-size: var(--my-change-base12-2x-size);
        color: var(--el-text-color-regular);
      }
    }
  }
</style>
